package com.idroc.coelacanth.service.servant;

import java.util.Iterator;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.idroc.coelacanth.core.dht.ConsistendHashNode;
import com.idroc.coelacanth.core.dht.ConsistentHashRing;
import com.idroc.coelacanth.core.dht.NodeActionObserver;
import com.idroc.coelacanth.core.membership.Endpoint;
import com.idroc.coelacanth.service.MessageService;

/**
 * 客户端代理
 * @author yuyoo (yuyoo4j@163.com)
 * @date 2009-12-17 下午01:15:37
 */
public class StorageClientBroker implements NodeActionObserver {
	
	private static final Logger log = LoggerFactory.getLogger(StorageClientBroker.class);
	
	private Endpoint remote = null;
	
	private Endpoint servant = null;
	
	private MessageService msgService = null;
	
	public void update(NodeAction na, int nodeNo, ConsistentHashRing ring) { 
		
		NodeActionNoticeMessage msg = new NodeActionNoticeMessage();
		msg.setFrom(servant);
		msg.setNodeNo(nodeNo);
		Iterator<ConsistendHashNode> it = ring.clockwiseNodeSequence(nodeNo, true);
		msg.setActor(it.next().getEndpoint());
		msg.setAction(na);
		msgService.sendMessage(remote, msg);
		log.debug("代理[{}]通知客户端, 消息[{}]", this, msg);
	}

	public Endpoint getServant() {
		return servant;
	}

	public void setServant(Endpoint servant) {
		this.servant = servant;
	}  
	
	public Endpoint getRemote() {
		return remote;
	}

	public void setRemote(Endpoint remote) {
		this.remote = remote;
	}

	public MessageService getMsgService() {
		return msgService;
	}

	public void setMsgService(MessageService msgService) {
		this.msgService = msgService;
	} 
	
	@Override
	public String toString() {

		StringBuilder sb = new StringBuilder();
		sb.append("StorageClientBroker[");
		sb.append("remote:").append(remote).append(",");
		sb.append("servant:").append(servant).append(",");
		sb.append("msgService:").append(msgService);
		sb.append("]");
		return sb.toString();
	}
}
